<template>
  <div>
    <el-container>
      <el-header>
        <div class="header">逻辑分析测评</div>
      </el-header>
      <el-main>
        <div class="container">
          <!-- 逻辑测评结果对话框 -->
          <el-dialog title="测评结果" v-model="showLogicReSultDialog" width="380px">
            <div style="text-align: center; margin-bottom: 20px">
              <p style="font-size: 24px; font-weight: 700">
                总得分:
                <span style="font-size: 24px; font-weight: 700; color: #00c853">
                  {{ score.total }}
                </span>
              </p>
            </div>
            <div style="margin-bottom: 20px">
              <div style="margin-bottom: 10px">文字分析：</div>
              <el-progress
                text-color="#fff"
                color="#20AD25"
                :text-inside="true"
                :stroke-width="15"
                :percentage="scoreRateByType.text"></el-progress>
            </div>
            <div style="margin-bottom: 20px">
              <div style="margin-bottom: 10px">图表分析：</div>
              <el-progress
                text-color="#fff"
                color="#060270"
                :text-inside="true"
                :stroke-width="15"
                :percentage="scoreRateByType.chart"></el-progress>
            </div>
            <div style="margin-bottom: 20px">
              <div style="margin-bottom: 10px">图形推理：</div>
              <el-progress
                text-color="#fff"
                color="#B6A724"
                :text-inside="true"
                :stroke-width="15"
                :percentage="scoreRateByType.graph"></el-progress>
            </div>

            <div class="dialog-footer">
              <el-button @click="showLogicReSultDialog = false">关闭</el-button>
            </div>
          </el-dialog>

          <div class="container-center" v-loading="loading">
            <div class="question-content">
              <!-- 题目 -->
              {{ currentQuestionNumber }}.
              <span class="question-content-title" v-html="currentQuestion.Title"></span>

              <!-- 选项 -->
              <div class="question-content-option">
                <div
                  v-for="(option, index) in currentQuestion.TopicOption"
                  :key="index"
                  v-html="option.OptionDescription"
                  class="question-content-option-item"
                  :class="{
                    correct:
                      selectedOption !== null &&
                      String.fromCharCode(65 + index) === currentQuestion.AnswerStr,
                    incorrect:
                      selectedOption !== null &&
                      String.fromCharCode(65 + index) === selectedOption &&
                      selectedOption !== currentQuestion.AnswerStr
                  }"
                  @click="selectOption(String.fromCharCode(65 + index))"></div>
              </div>

              <!-- 正确答案和解析 -->
              <div
                class="answer-explanation-box"
                v-if="selectedOption"
                :class="{
                  correct: selectedOption === currentQuestion.AnswerStr,
                  incorrect: selectedOption !== currentQuestion.AnswerStr
                }">
                <div class="answer">
                  正确答案是：
                  <span>{{ currentQuestion.AnswerStr }}</span>
                </div>
                <div class="explanation">
                  解析：
                  <span class="explanation-content" v-html="currentQuestion.Description"></span>
                </div>
              </div>

              <!-- 导航按钮 -->
              <div class="nav-buttons">
                <el-button
                  style="padding: 12px 20px; background-color: #2d4ff4; border: #2d4ff4"
                  type="primary"
                  @click="prevQuestion"
                  :disabled="currentQuestionIndex === 0">
                  上一题
                </el-button>
                <div class="question-info">
                  <span>{{ currentQuestionNumber }}/{{ totalQuestions }}</span>
                </div>
                <el-button
                  style="padding: 12px 20px; background-color: #2d4ff4; border: #2d4ff4"
                  type="primary"
                  @click="nextQuestion">
                  下一题
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { evaulationStore } from "@/store";
import { toast } from "@/components/util";

const MAX_SWITCH_TIMES = 3;
const tabSwitchTimes = ref(0);
const frontStore = evaulationStore();
const loading = ref(true);
const questions = ref([]);
const currentQuestionIndex = ref(0);
const userAnswers = ref([]);
const selectedOption = ref(null);
const answered = ref([]);
const showLogicReSultDialog = ref(false);
const isSubmitData = ref(false);
const scoreRateByType = ref({ text: 0, chart: 0, graph: 0 });
const score = ref({ text: 0, chart: 0, graph: 0, total: 0 });
const correctAnswer = ref({ text: 0, chart: 0, graph: 0 });
const errorAnswer = ref({ text: 0, chart: 0, graph: 0 });
const typeMap = { 1: "text", 2: "chart", 3: "graph" };

const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value] || {};
});

const totalQuestions = computed(() => {
  return questions.value.length;
});

const handleVisibilityChange = () => {
  if (document.visibilityState === "hidden") {
    tabSwitchTimes.value++;
    toast("请勿切屏！连续三次切屏则会刷新页面重新进行答题", "warning");
    console.log(tabSwitchTimes.value);
  }
  if (tabSwitchTimes.value > MAX_SWITCH_TIMES) {
    setTimeout(() => {
      tabSwitchTimes.value = 0;
      toast("已连续三次警告，请重新答题！", "error");
      location.reload();
    }, 0);
  }
};

onMounted(() => {
  document.addEventListener("visibilitychange", handleVisibilityChange);
});

onUnmounted(() => {
  document.removeEventListener("visibilitychange", handleVisibilityChange);
});

const currentQuestionNumber = computed(() => {
  return currentQuestionIndex.value + 1;
});

const currentTypeName = computed(() => {
  // currentQuestion 是 computed 返回的对象，直接访问其属性（已自动解包）
  return typeMap[currentQuestion.value.RepositoryId] || "";
});

// ------------------------------ 核心方法 ------------------------------
/** 获取题目列表 */
const fetchQuestions = async () => {
  loading.value = true;
  try {
    // const res = await frontStore.getLogicTest();
    const res = await fetch("/exam.json");
    const responseData = await res.json();
    // 打平并随机排序题目
    const allTopics = responseData.Data.flatMap((item) => item.TopicInfo);
    // 注意：questions 是 ref，需通过 .value 访问数组的 splice 方法
    questions.value.splice(0, questions.value.length, ...randomSort(allTopics));
  } catch (error) {
    console.error("获取题目失败:", error);
  } finally {
    loading.value = false;
  }
};

/** 选择选项 */
const selectOption = (option) => {
  // 注意：answered 是 ref，需通过 .value 访问数组
  if (answered.value[currentQuestionIndex.value]) return;

  selectedOption.value = option;
  const currentIndex = currentQuestionIndex.value;
  const currentType = currentTypeName.value;

  // 判断答案是否正确并更新分数
  if (option === currentQuestion.value.AnswerStr) {
    // correctAnswer 是 ref，需通过 .value 访问对象属性
    correctAnswer.value[currentType]++;
    // score 是 ref，需通过 .value 访问对象属性
    score.value[currentType] += 4;
    score.value.total += 4;
  } else {
    errorAnswer.value[currentType]++;
  }

  // 记录用户答案和答题状态（userAnswers 和 answered 是 ref）
  userAnswers.value[currentIndex] = option;
  answered.value[currentIndex] = true;
};

/** 下一题 */
const nextQuestion = () => {
  if (selectedOption.value === null) {
    ElMessage.warning("请选择一个选项");
    return;
  }

  // 最后一题：计算分数 → 提交数据 → 显示结果弹窗
  if (currentQuestionIndex.value === totalQuestions.value - 1) {
    calculateScore();
    submitData();
    showLogicReSultDialog.value = true;
    return;
  }

  // 切换到下一题（userAnswers 是 ref）
  currentQuestionIndex.value++;
  selectedOption.value = userAnswers.value[currentQuestionIndex.value] || null;
};

/** 上一题 */
const prevQuestion = () => {
  if (currentQuestionIndex.value === 0) return;
  currentQuestionIndex.value--;
  selectedOption.value = userAnswers.value[currentQuestionIndex.value] || null;
};

/** 关闭结果弹窗 */
const handleDialogClose = () => {
  showLogicReSultDialog.value = false;
};

/** 随机排序数组 */
const randomSort = (arr) => {
  return [...arr].sort(() => Math.random() - 0.5);
};

/** 计算得分率 */
const calculateScore = () => {
  // correctAnswer、errorAnswer、scoreRateByType 是 ref，需通过 .value 访问
  const totalByType = {
    text: correctAnswer.value.text + errorAnswer.value.text,
    chart: correctAnswer.value.chart + errorAnswer.value.chart,
    graph: correctAnswer.value.graph + errorAnswer.value.graph
  };

  const totalScoreByType = {
    text: totalByType.text * 4,
    chart: totalByType.chart * 4,
    graph: totalByType.graph * 4
  };

  // scoreRateByType 和 score 是 ref，需通过 .value 访问
  scoreRateByType.value.text =
    totalByType.text > 0 ? Math.round((score.value.text / totalScoreByType.text) * 100) : 0;
  scoreRateByType.value.chart =
    totalByType.chart > 0 ? Math.round((score.value.chart / totalScoreByType.chart) * 100) : 0;
  scoreRateByType.value.graph =
    totalByType.graph > 0 ? Math.round((score.value.graph / totalScoreByType.graph) * 100) : 0;
};

/** 提交答题结果 */
const submitData = async () => {
  if (isSubmitData.value) return;

  try {
    await axios.post("https://mp.olinking.com/API/Evaluation/AddTopicResult", {
      Score: score.value.total, // score 是 ref，需通过 .value 访问
      Result: {
        totalScore: score.value.total, // score 是 ref，需通过 .value 访问
        textAnalysis: scoreRateByType.value.text, // scoreRateByType 是 ref，需通过 .value 访问
        chartAnalysis: scoreRateByType.value.chart, // scoreRateByType 是 ref，需通过 .value 访问
        graphReasoning: scoreRateByType.value.graph // scoreRateByType 是 ref，需通过 .value 访问
      }
    });
    isSubmitData.value = true; // 标记已提交
  } catch (error) {
    console.error("提交结果失败:", error);
  }
};

// ------------------------------ 初始化 ------------------------------
// 组件加载时自动获取题目（类似 Vue 2 的 created 钩子）
fetchQuestions();
handleVisibilityChange();
</script>

<style scoped>
.el-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.el-header {
  padding: 0;
}

.el-main {
  padding: 0;
  height: 100%;
}

* {
  padding: 0px;
  margin: 0px;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: 700;
  color: rgb(14, 146, 255);
  width: 100%;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.container {
  display: flex;
  position: relative;
  justify-content: center;
  background: linear-gradient(to bottom right, #88d3f6a1, #fff);
  padding: 30px 10px;
  min-height: 100%;
}

.container-center {
  width: 1000px;
  max-width: 100%;
  padding: 20px 40px;
  background-color: #ffffffcc;
  font-size: 18px;
  border-radius: 10px;
  overflow-wrap: break-word;
  word-break: break-word;
}

.question-info {
  display: flex;
  justify-content: space-between;
  font-size: 20px;
  color: #666;
  font-weight: 700;
}

.question-content {
  margin-top: 20px;
}

:deep(img) {
  max-width: 100%;
}

.question-content-option-item {
  margin-top: 20px;
  padding: 15px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s;
  border: 1px solid #eee;
}

.question-content-option-item:hover {
  background-color: #f0f5ff;
  border-color: #2d4ff4;
}

.question-content-option-item.correct {
  background-color: #0e9202;
  color: #fff;
  border-color: #0e9202;
}

.question-content-option-item.incorrect {
  background-color: #ff6161;
  color: #fff;
  border-color: #ff6161;
}

.answer-explanation-box {
  margin-top: 20px;
  padding: 15px;
  border-radius: 5px;
  border: 1px solid #eee;
}

.answer-explanation-box.correct {
  background-color: rgba(18, 198, 2, 0.1);
  border-color: #13c602;
}

.answer-explanation-box.incorrect {
  background-color: rgba(255, 97, 97, 0.1);
  border-color: #ff6161;
}

.answer {
  margin-bottom: 10px;
  font-size: 16px;
}

.answer span {
  font-weight: bold;
  color: #00c853;
}

.explanation {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.explanation-content {
  font-style: italic;
}

.nav-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  margin-bottom: 20px;
}

.nav-buttons .el-button {
  padding: 12px 20px;
  background-color: #2d4ff4;
  border: #2d4ff4;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.nav-buttons .el-button:hover {
  background-color: #1a3cd4;
}

.nav-buttons .question-info {
  font-size: 18px;
  color: #666;
}
</style>